package com.macro.mall.portal.util;

import cn.hutool.core.date.DateTime;
import com.macro.mall.portal.config.TencentCOSConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class COSUtil {

    private static final String BUCKET_NAME = "91mall-1382151393";
    // 所在地域
    private static final String REGION = "ap-shanghai";
    // COS 访问域名前缀（自定义或默认）
    private static final String BASE_URL = "https://" + BUCKET_NAME + ".cos." + REGION + ".myqcloud.com/";

    public static String uploadFile(MultipartFile file) throws IOException {
        COSClient cosClient = TencentCOSConfig.initCOSClient(); // 初始化客户端
        InputStream inputStream = file.getInputStream();
        String fileName = file.getOriginalFilename();

        // 1️⃣ 获取文件后缀名
        String extension = fileName.substring(fileName.lastIndexOf("."));

        // 2️⃣ 生成唯一文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = uuid + extension;

        // 3️⃣ 使用当前日期作为文件夹路径，例如：2025/10/24/xxxx.jpg
        String timeFolder = new DateTime().toString("yyyy/MM/dd");
        String key = timeFolder + "/" + newFileName;

        try {
            // 4️⃣ 设置文件元信息（可选）
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());

            // 5️⃣ 上传文件
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, inputStream, metadata);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

            System.out.println("上传成功，ETag：" + putObjectResult.getETag());

            // 6️⃣ 返回文件访问路径
            return BASE_URL + key;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败", e);
        } finally {
            cosClient.shutdown(); // 关闭客户端连接
            inputStream.close();
        }
    }
}
